#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
//#include "log.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage :" << proc << "service_ip  service_port" << std::endl;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 创建套接字。
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        std::cerr << "socket fail" << std::endl;
        exit(2);
    } 

    // 建立链接
    // int connect(int sockfd, const struct sockaddr *addr,
                    //    socklen_t addrlen);
    struct sockaddr_in local;
    local.sin_port = htons(port);
    // int inet_pton(int af, const char *src, void *dst);
    void* dst = nullptr;
    inet_pton(AF_INET,ip.c_str(),&(local.sin_addr));
    connect(AF_INET,(const struct sockaddr *)&local,sizeof(local));

    while(true)
    {
        std::cout << "Please Enter # ";
        std::string message;
        std::getline(std::cin,message);
        write(sockfd,message.c_str(),message.size());

        char buffer[1024];
        ssize_t n = read(sockfd,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}